import { resolve } from 'node:path'; // 跨平台一致的文件路径处理

import dayjs from 'dayjs';
import { readPackageJSON } from 'pkg-types'; // 管理和操作package.json与tsconfig.json等配置文件，读取、写入、解析配置文件
import { defineConfig, loadEnv, mergeConfig, type UserConfig } from 'vite';

import { createPlugins } from '../plugins';
import { generateModifyVars } from '../utils/modifyVars';
import { commonConfig } from './common';

interface DefineOptions {
  overrides?: UserConfig;
  options?: {
    //
  };
}

function defineApplicationConfig(defineOptions: DefineOptions = {}) {
  const { overrides = {} } = defineOptions;

  return defineConfig(async ({ command, mode }) => {
    const root = process.cwd();
    const isBuild = command === 'build';
    const { VITE_PUBLIC_PATH, VITE_USE_MOCK, VITE_BUILD_COMPRESS, VITE_ENABLE_ANALYZE } = loadEnv(
      mode,
      root,
    ); // 加载环境变量。根据 mode 模式加载配置不同环境的设置
    console.log(VITE_ENABLE_ANALYZE === 'true')
    console.log(VITE_USE_MOCK === 'true')

    const defineData = await createDefineData(root);
    const plugins = await createPlugins({
      isBuild,
      root,
      enableAnalyze: VITE_ENABLE_ANALYZE === 'true',
      enableMock: VITE_USE_MOCK === 'true',
      compress: VITE_BUILD_COMPRESS,
    });

    const pathResolve = (pathname: string) => resolve(root, '.', pathname); // 路径解析
    console.log(resolve(root, '.', 'src'))

    const applicationConfig: UserConfig = {
      base: VITE_PUBLIC_PATH, // 项目基础路径，通常用于降项目部署到子路径的情况
      resolve: {
        alias: [ // 路径别名，
          {
            find: 'vue-i18n',
            replacement: 'vue-i18n/dist/vue-i18n.cjs.js',
          },
          // @/xxxx => src/xxxx
          {
            find: /@\//,
            replacement: pathResolve('src') + '/',
          },
          // #/xxxx => types/xxxx
          {
            find: /#\//,
            replacement: pathResolve('types') + '/',
          },
        ],
      },
      define: defineData, // package.json配置信息
      build: {
        target: 'es2015',
        cssTarget: 'chrome80',
        rollupOptions: {
          output: {
            // 入口文件名
            entryFileNames: 'assets/entry/[name]-[hash].js',
            manualChunks: {
              vue: ['vue', 'pinia', 'vue-router']
              // antd: ['ant-design-vue', '@ant-design/icons-vue'], // 这里到时替换成elementplus
            },
          },
        },
      },
      css: {
        preprocessorOptions: { // css 预处理器
          less: {
            modifyVars: generateModifyVars(), // 动态生成 less 变量
            javascriptEnabled: true, // 允许在 less 中使用 JavaScript 表达式
          },
        },
      },
      plugins,
    };

    const mergedConfig = mergeConfig(commonConfig(mode), applicationConfig);

    return mergeConfig(mergedConfig, overrides);
  });
}

async function createDefineData(root: string) {
  try {
    const pkgJson = await readPackageJSON(root); // 读取项目根目录下 package.json 返回配置对象
    const { dependencies, devDependencies, name, version } = pkgJson;

    const __APP_INFO__ = {
      pkg: { dependencies, devDependencies, name, version },
      lastBuildTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    };
    return {
      __APP_INFO__: JSON.stringify(__APP_INFO__),
    };
  } catch (error) {
    return {};
  }
}

export { defineApplicationConfig };
